package com.vvv.method;

import sun.misc.Unsafe;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author vvv
 * @date 2023-10-20 16 17
 * discription
 */
public class MyAtomicInteger {
    public static void main(String[] args) {
    }

    private static final Unsafe unsafe;
    private static final long valueOffest;

    private volatile int value;


    static {
        unsafe = Unsafe.getUnsafe();
        try {
            valueOffest = unsafe.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

    public long get() {
        return this.value;
    }

    public void increment(int num) {
        while (true) {
            int pre = this.value;
            int next = value - num;
            if (unsafe.compareAndSwapInt(this, valueOffest, pre, next)) {
                break;
            }
        }
    }
}
